package com.cskaoyan.service.impl;

import com.cskaoyan.bean.CatAndBrandData;
import com.cskaoyan.bean.GoodsParameter;
import com.cskaoyan.bean.PageData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.GoodsCreateVo;
import com.cskaoyan.bean.vo.GoodsDetailVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.*;
import com.cskaoyan.service.GoodsService;
import com.cskaoyan.utils.MyBatisUtil;
import com.cskaoyan.utils.TransactionUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class GoodsServiceImpl implements GoodsService {
    @Override
    public void create(SqlSession sqlSession, MarketGoods goods) {
        MarketGoodsMapper goodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        goodsMapper.insertSelective(goods);
    }

    @Override
    public PageData goodsList(GoodsParameter goodsParameter) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketGoodsMapper marketGoodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);

        //这个地方是优惠券管理的地方调用的情况
        if (goodsParameter.getLimit() == 0){
            List<MarketGoods> marketGoods = marketGoodsMapper.selectAll();
            PageData data = new PageData();
            data.setTotal(marketGoods.size());
            data.setList(marketGoods);
            data.setPages(0);
            data.setLimit(0);
            return data;
        }

        //开启分页
        //使用example来进行响应分页
        PageHelper.startPage(goodsParameter.getPage(), goodsParameter.getLimit());

        MarketGoodsExample example = new MarketGoodsExample();
        //排序
        example.setOrderByClause(goodsParameter.getSort() + " " + goodsParameter.getOrder());

        //便于进行逻辑删除，以后查询的所有参数都是没有被删除的
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);

        //条件查询，进行条件的拼接
        Integer id = goodsParameter.getGoodsId();
        if (id != null && id != 0) {
            criteria.andIdEqualTo(id);
        }
        //此时商品编号为模糊匹配
        if (goodsParameter.getGoodsSn() != null && !goodsParameter.getGoodsSn().isEmpty()) {
            criteria.andGoodsSnLike("%" + goodsParameter.getGoodsSn() + "%");
        }
        if (goodsParameter.getName() != null && !goodsParameter.getName().isEmpty()) {
            criteria.andNameLike("%" + goodsParameter.getName() + "%");
        }

        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(example);

        //调用PageData的list对响应的PageData进行封装
        PageData data = PageData.list(marketGoods);

        //连接在最后结束前进行关闭
        sqlSession.close();


        return data;
    }

    @Override
    public BaseRespVo updateGoods(GoodsCreateVo goodsCreateVo) {
        //此时要为四个表格进行更新，所以需要同时提交，使用同一个事务
        //开启事务
        TransactionUtil.startTransaction();
        //获得SqlSession
        SqlSession sqlSession = TransactionUtil.getSqlSession();

        //提供一个添加时间
        Date date = new Date();

        //MarketGoods goods→向goods表中更新数据
        MarketGoodsMapper marketGoodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        //通过请求参数转化的对象，然后得到其中的Marketgoods
        MarketGoods goods = goodsCreateVo.getGoods();
        //更新表时要保证goodsSn和name不为空
        if (goods.getGoodsSn() == null || goods.getGoodsSn().isEmpty()) {
            return BaseRespVo.fail("参数不对", 401);
        }
        //更新表时要保证goodsSn和name不为空
        if (goods.getName() == null || goods.getName().isEmpty()) {
            return BaseRespVo.fail("参数不对", 401);
        }
        //给goods对象设置更新和添加时间
        goods.setAddTime(date);
        goods.setUpdateTime(date);
        marketGoodsMapper.updateByPrimaryKeySelective(goods); //插入到表格以后会生成自增的主键，作为接下来插入的表中的goods_id字段值
        Integer goodsId = goods.getId();


        //List<MarketGoodsSpecification> specifications → 向specification表中更新数据
        MarketGoodsSpecificationMapper marketGoodsSpecificationMapper = sqlSession.getMapper(MarketGoodsSpecificationMapper.class);
        List<MarketGoodsSpecification> specifications = goodsCreateVo.getSpecifications();
        //循环遍历该集合List中的每一个MarketGoodsSpecification对象，然后对每个对象添加更新时间和创建时间
        for (MarketGoodsSpecification specification : specifications) {
            specification.setAddTime(date);
            specification.setUpdateTime(date);
            specification.setGoodsId(goodsId);
            marketGoodsSpecificationMapper.updateByPrimaryKeySelective(specification);

        }


        //List<MarketGoodsProduct> products → 向product表中更新数据
        MarketGoodsProductMapper marketGoodsProductMapper = sqlSession.getMapper(MarketGoodsProductMapper.class);
        List<MarketGoodsProduct> products = goodsCreateVo.getProducts();
        for (MarketGoodsProduct product : products) {
            product.setAddTime(date);
            product.setUpdateTime(date);
            product.setGoodsId(goodsId);
            //将封装的数据增加到相应的表中，调用mapper中的方法
            marketGoodsProductMapper.updateByPrimaryKeySelective(product);
        }

        //List<MarketGoodsAttribute> attributes → 向attribute表中添加数据
        MarketGoodsAttributeMapper marketGoodsAttributeMapper = sqlSession.getMapper(MarketGoodsAttributeMapper.class);
        List<MarketGoodsAttribute> attributes = goodsCreateVo.getAttributes();
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goodsId);
            attribute.setAddTime(date);
            attribute.setUpdateTime(date);
            marketGoodsAttributeMapper.updateByPrimaryKeySelective(attribute);

        }

        //事务提交
        TransactionUtil.commit();
        sqlSession.close();

        return BaseRespVo.ok(null);
    }

    @Override
    public BaseRespVo detailGoods(Integer id) {
        //此时要为四个表格进行更新，所以需要同时提交，使用同一个事务
        //开启事务
        TransactionUtil.startTransaction();
        //获得SqlSession
        SqlSession sqlSession = TransactionUtil.getSqlSession();

        MarketGoodsMapper marketGoodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        //用于封装响应的对象
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        Integer categoryId = marketGoods.getCategoryId();


        //如果categoryId为空，则返回错误,此时为属性id
        if (categoryId == null || categoryId == 0) {
            return BaseRespVo.fail("系统内部错误", 502);
        }
        goodsDetailVo.setGoods(marketGoods);


        Integer goodsId = id;
        //查询所有的specifications
        MarketGoodsSpecificationMapper marketGoodsSpecificationMapper = sqlSession.getMapper(MarketGoodsSpecificationMapper.class);
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsSpecification> specifications = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
        goodsDetailVo.setSpecifications(specifications);

        //查询所有的prodects
        MarketGoodsProductMapper marketGoodsProductMapper = sqlSession.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsProduct> products = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
        goodsDetailVo.setProducts(products);

        //查找所有的attributes
        MarketGoodsAttributeMapper marketGoodsAttributeMapper = sqlSession.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsAttribute> attributes = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        goodsDetailVo.setAttributes(attributes);


        //根据id来查找categoryId列表
        MarketCategoryMapper marketCategoryMapper = sqlSession.getMapper(MarketCategoryMapper.class);
        MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(categoryId);
        Integer pid = marketCategory.getPid();
        List<Integer> categoryIds = new ArrayList<>();
        categoryIds.add(categoryId);
        if (pid != 0) {
            categoryIds.add(pid);
        }
        goodsDetailVo.setCategoryIds(categoryIds);

        //事务提交
        TransactionUtil.commit();
        sqlSession.close();

        return BaseRespVo.ok(goodsDetailVo);
    }

    @Override
    public CatAndBrandData catAndBrand() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketCategoryMapper marketCategoryMapper = sqlSession.getMapper(MarketCategoryMapper.class);
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(marketCategoryExample);
        MarketBrandMapper marketBrandMapper = sqlSession.getMapper(MarketBrandMapper.class);
        MarketBrandExample marketBrandExample = new MarketBrandExample();
        List<MarketBrand> marketBrands = marketBrandMapper.selectByExample(marketBrandExample);

        //Map<Integer, String> map = marketBrands.stream().collect(Collectors.toMap(MarketBrand::getId, MarketBrand::getName));

        //建立大的CatAndBrandData对象
        CatAndBrandData catAndBrandData = new CatAndBrandData();
        //封装品牌列表
        ArrayList<CatAndBrandData.BrandListDTO> brandList = new ArrayList<>();
        for (MarketBrand marketBrand : marketBrands) {
            CatAndBrandData.BrandListDTO brandListDTO = new CatAndBrandData.BrandListDTO();
            Integer value = marketBrand.getId();
            String label = marketBrand.getName();
            brandListDTO.setLabel(label);
            brandListDTO.setValue(value);
            brandList.add(brandListDTO);
        }
        //添加brandList到catAndBrandData中
        catAndBrandData.setBrandList(brandList);

        //封装分类列表
        ArrayList<CatAndBrandData.CategoryListDTO> categoryList = new ArrayList<>();
        //遍历得到分类列表
        for (MarketCategory marketCategory : marketCategories) {
            CatAndBrandData.CategoryListDTO categoryListDTO = new CatAndBrandData.CategoryListDTO();
            //通过id来得到其value
            Integer value = marketCategory.getId();
            //通过name来得到其label
            String label = marketCategory.getName();
            categoryListDTO.setLabel(label);
            categoryListDTO.setValue(value);
            List<CatAndBrandData.CategoryListDTO.ChildrenDTO> children = new ArrayList<>();
            for (MarketCategory category : marketCategories) {
                if (Objects.equals(category.getPid(), value)) {
                    CatAndBrandData.CategoryListDTO.ChildrenDTO childrenDTO = new CatAndBrandData.CategoryListDTO.ChildrenDTO();
                    childrenDTO.setLabel(category.getName());
                    childrenDTO.setValue(category.getId());
                    children.add(childrenDTO);
                }
            }
            categoryListDTO.setChildren(children);
            categoryList.add(categoryListDTO);
        }
        //添加categoryList到catAndBrandData中
        catAndBrandData.setCategoryList(categoryList);

        sqlSession.commit();
        sqlSession.close();
        return catAndBrandData;

    }

    @Override
    public BaseRespVo deleteGoods(MarketGoods marketGoodes) {

        //开启事务
        TransactionUtil.startTransaction();
        //同时删除需要开启事务，并同时进行删除
        SqlSession sqlSession = TransactionUtil.getSqlSession();

        //对MarketGoods进行逻辑删除，设置其值为true
        marketGoodes.setDeleted(true);
        MarketGoodsMapper marketGoodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        marketGoodsMapper.updateByPrimaryKeySelective(marketGoodes);
        //从MarketGoods表中得到Id作为其他表的goodsId
        Integer goodsId = marketGoodes.getId();


        //对MarketGoodsProduct进行逻辑删除
        MarketGoodsProductMapper marketGoodsProductMapper = sqlSession.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId);
        //通过goodsId来查找所有的MarketGoodsProduct，并修改其deleted的值
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
        for (MarketGoodsProduct marketGoodsProduct : marketGoodsProducts) {
            marketGoodsProduct.setDeleted(true);
            //更新MarketGoodsProduct表
            marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct);
        }

        //对MarketGoodsAttribute进行逻辑删除
        MarketGoodsAttributeMapper marketGoodsAttributeMapper = sqlSession.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodsId);
        //通过goodsId来查找所有的MarketGoodsAttribute，并修改其deleted的值
        List<MarketGoodsAttribute> marketGoodsAttributes = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        for (MarketGoodsAttribute marketGoodsAttribute : marketGoodsAttributes) {
            marketGoodsAttribute.setDeleted(true);
            //更新MarketGoodsAttribute表
            marketGoodsAttributeMapper.updateByPrimaryKeySelective(marketGoodsAttribute);
        }

        //对MarketGoodsSpecification进行逻辑删除
        MarketGoodsSpecificationMapper marketGoodsSpecificationMapper = sqlSession.getMapper(MarketGoodsSpecificationMapper.class);
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsSpecification> marketGoodsSpecifications = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
        for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
            marketGoodsSpecification.setDeleted(true);
            //更新MarketGoodsSpecification表
            marketGoodsSpecificationMapper.updateByPrimaryKeySelective(marketGoodsSpecification);
        }


        //提交事务
        TransactionUtil.commit();
        //关闭sqlSession
        sqlSession.close();

        return BaseRespVo.ok(null);

    }


}
